package cn.liccshop.core.service.shopProducts.service;

import cn.liccshop.core.entity.ShopGoods;
import cn.liccshop.core.entity.ShopProducts;
import cn.liccshop.core.service.shopGoods.mapper.ShopGoodsMapper;
import cn.liccshop.core.service.shopProducts.mapper.ShopProductsMapper;
import cn.liccshop.core.service.shopProducts.service.IShopProductsService;
import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.exception.MySystemException;
import cn.liccshop.sys.utils.MapToObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品基本属性表 服务实现类
 * </p>
 *
 * @author LiCC
 * @since 2019-04-08
 */
@Service
public class ShopProductsServiceImpl extends ServiceImpl<ShopProductsMapper, ShopProducts> implements IShopProductsService {

    @Autowired
    private ShopGoodsMapper goodsMapper;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public boolean saveInfos(Map<String, Object> map) throws MySystemException {
        /** 拿到商品信息，主要修改状态和库存 **/
        ShopGoods goods = MapToObjectUtil.mapToEntity((Map<String, Object>) map.get("goodsInfo"), ShopGoods.class);
        /** 获取商品属性值对应的库存、警报库存和价格 **/
        List<ShopProducts> products = MapToObjectUtil.mapToList((JSONArray) map.get("products"), ShopProducts.class);
        if (goods==null|| CollectionUtils.isEmpty(products)){
            throw new MySystemException("参数异常！", Constants.SERVICE_FAIL);
        }
        for(ShopProducts product : products){
            if (StringUtils.isBlank(product.getId())){
                /** ID为空，说明信息是保存不是插入 **/
                baseMapper.insert(product);
            } else {
                baseMapper.updateById(product);
            }
        }
        goodsMapper.updateById(goods);
        return true;
    }
}
